package api

import (
	"errors"
	"strings"

	"jgt-oper/src/bll"
	"jgt-oper/src/context"
	"jgt-oper/src/schema"
)

// Dictionary 字典表管理
type Dictionary struct {
	DictionaryBll *bll.Dictionary `inject:""`
}

// QueryTree 查询树形数据
func (a *Dictionary) QueryTree(ctx *context.Context) error {
	code := ctx.Query("code")
	if len(strings.Split(code, "$#")) < 3 {
		return ctx.ResErrBadRequest(errors.New("请求参数异常"))
	}
	level := 1

	items, err := a.DictionaryBll.QuerySimpleTree(code, level)
	if err != nil {
		return ctx.ResErrInternalServer(err)
	}
	return ctx.ResSuccess(items)
}

// GetByCode 根据Code获取名字
func (a *Dictionary) GetByCode(ctx *context.Context) error {
	var (
		item       *schema.Dictionary
		err        error
		name, code string
	)
	code = ctx.Query("code")
	if len(strings.Split(code, "$#")) < 3 {
		return ctx.ResErrBadRequest(errors.New("请求参数异常"))
	}
	item, err = a.DictionaryBll.GetByCode(code)
	if err != nil {
		return ctx.ResErrBadRequest(err)
	}
	name = item.Name
	return ctx.ResSuccess(name)
}
